import { asyncRoutes, constantRoutes } from '@/router'

// 检查是否有权限
export function hasPermission(roles, route) {
  if (roles && route.name) {
    return roles.some(role => {
      return route.name.toLowerCase() === role.toLowerCase()
    })
  } else {
    return false
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
export function filterAsyncRouter(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}


const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTERS: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      //动态构造权限列表
      let accessedRouters = filterAsyncRouter(asyncRoutes, roles)
      commit('SET_ROUTERS', accessedRouters)
      //commit('SET_ROUTERS', asyncRouterMap) // 调试开启全部路由
      resolve(accessedRouters)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
